package org.ms.nerver.governor.proxy;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 基于Cglib实现动态代理工厂
 * @author lry
 */
public abstract class CglibAbstractProxyFactory implements ProxyService,MethodInterceptor {

	private Object object;

	public CglibAbstractProxyFactory(Object object) {
		this.object=object;
	}
	
	/**
	 * 创建代理对象
	 * @param <T>
	 * @param object
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T getService(Class<T> clazz) throws Throwable {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(object.getClass());
		enhancer.setCallback(this);// 回调方法
		return (T) enhancer.create();// 创建代理对象
	}

	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		if(proxy==null||object==null){
			throw new RuntimeException("proxy或method不能为空");
		}
		System.out.println("======"+proxy.getClass());
		doBefore(proxy, method, args);// 调用之前
		Object result = doInvoke(method, proxy, args, methodProxy);// 调用原始对象的方法
		doAfter(proxy, method, args,result);// 调用之后
		
		return result;
	}
	
	public Object doInvoke(Method method, Object proxy, Object[] args, Object...others) throws Throwable {
		if(others!=null){
			for (Object object:others) {
				if(object instanceof MethodProxy){
					MethodProxy methodProxy=(MethodProxy) object;
					return  methodProxy.invokeSuper(proxy, args);	
				}
				
			}
		}
		throw new RuntimeException("'"+method+"' was not found.");
	}
	
}